import {Item, OrderBundle, WithId} from '@/store/modules/types/Bundle'
import {Asset} from '@/store/modules/types/Asset'
import {AssetStock} from '@/store/modules/types/AssetStock'

const state = {
  bundles: [] as OrderBundle[],
  selectedBundles: [] as OrderBundle[]
}


function toggleBundleSelect(bundle: OrderBundle, isSelect: boolean) {
  Object.assign(bundle, { isSelected: isSelect })
  bundle.items.forEach((item: Item) => {
    Object.assign(item, { selected: null, isSelected: isSelect })
  })
  // if isSelect is true pick the first available asset for each criterion
  if (isSelect) {
    bundle.items.forEach((item: Item, index: number) => {
      // TODO Need do more validate for the first avaliable asset
      // NOTE Here only for sample pick the first asset for each criterion
      if (item.data.length > 0) {
        Object.assign(item, { selected: 0 })
      }
    })
  }
  return bundle
}

const mutations = {
  dummy(state: any) {
    // do nothing
  },
  updateBundles(state: any, bundles: OrderBundle[]) {
    // 1. add selected flag for each bundle and it's assets
    bundles.forEach((bundle: OrderBundle) => {
      toggleBundleSelect(bundle, false)
    })
    state.bundles = bundles
  },
  selectBundle(state: any, { bundle, isSelect }: { bundle: OrderBundle, isSelect: boolean }) {
    toggleBundleSelect(bundle, isSelect)
    let index = state.bundles.findIndex((item: WithId) => item.id == bundle.id)
    if (index !== -1) state.bundles.splice(index, 1, bundle)
  },
  resetBundles(state: any) {
    state.bundles = []
  }
}

const actions = {}

const getters = {
  bundleSelectedAssets(state: any): { assets: Asset[], assetStocks: AssetStock[] } {
    let assets: Asset[] = []
    let assetStocks: AssetStock[] = []
    state.bundles.forEach((bundle: OrderBundle) => {
      bundle.items.forEach((item: Item) => {
        if (item.selected != null && item.selected != undefined) {
          let asset: Asset | AssetStock = item.data[item.selected]
          if (asset.type == 'App\\Models\\Asset') {
            assets.push(asset as Asset)
          } else {
            assetStocks.push(asset as AssetStock)
          }
        }
      })
    })
    return { assets, assetStocks }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
